import { Config, CONFIG_PROJECT, CONFIG_SEVER } from "../Data/Config";
import { StaticData } from "../Data/StaticData";
import { EventNames } from "../Home/Data/EventNames";
import { WXLogin } from "../Tools/WXLogin";

export default class HttpManager {

    //TODO: 测试用的地址，后端更新后需要替换
    public static url: string = CONFIG_SEVER + CONFIG_PROJECT

    public static post(url: string, params: any = null, headers: any = null) {
        return this.postUrl(this.url + url, params, headers);
    }
    public static postUrl(url: string, params: any = null, headers: any = null) {
        return new Promise((resolve: (data: HttpReturn) => void, reject) => {
            let xhr = new XMLHttpRequest();
            const now = new Date();
            const timeStr = `${now.getHours().toString()}:${now.getMinutes().toString()}:${now.getSeconds().toString()}`;
            console.log("HTTP POST",timeStr,url,params);
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            StaticData.getToken() && xhr.setRequestHeader("X-Access-Token", StaticData.getToken());
            if (headers) {
                for (let key in headers) {
                    xhr.setRequestHeader(key, headers[key]);
                }
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                    let response = xhr.responseText;
                    console.log(xhr.responseURL);
                    let rsp = JSON.parse(response);
                    console.log(response + "   " + url);
                    resolve(rsp);
                } else if (xhr.readyState == 4) {
                    reject(); 
                } else {
                    // console.log("url=>" + url + " xhr.readyState=>" + xhr.readyState + "; status=>" + xhr.status);
                }
            }
            xhr.timeout = 8000;
            console.log(params);
            console.log(JSON.stringify(params));
            xhr.send(JSON.stringify(params));
        });
    }
    public static get(url: string, data: any = null, headers: any = null): Promise<any> {
        return this.getUrl(this.url + url, data, headers);
    }
    public static getUrl(url: string, data: any = null, headers: any = null): Promise<any> {
        return new Promise((resolve: (data: HttpReturn) => void, reject) => {
            let xhr = new XMLHttpRequest();
            let dataStr = "";
            if (data) {
                Object.keys(data).forEach(key => {
                    dataStr += key + '=' + data[key] + '&';
                });
                //匹配最后一个&并去除
                if (dataStr !== '') {
                    dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
                }
            }
            let newUrl = url;
            if(dataStr){
                newUrl = url + "?" + dataStr;
            }
            const now = new Date();
            const timeStr = `${now.getHours().toString()}:${now.getMinutes().toString()}:${now.getSeconds().toString()}`;
            console.log("HTTP get",timeStr,newUrl);
            xhr.open("GET", newUrl, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            StaticData.getToken() && xhr.setRequestHeader("X-Access-Token", StaticData.getToken());
            if (headers) {
                for (let key in headers) {
                    xhr.setRequestHeader(key, headers[key]);
                }
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                    let response = xhr.responseText;
                    let rsp = JSON.parse(response);
                    console.log(url, "=>|", response);
                    if (rsp && rsp.code && rsp.code == 403) {
                        console.log("403 Token过期，重新认证");
                        Laya.stage.event(EventNames.POP_403_COMMON_TIPS)
                        reject();
                        console.log("11 true");
                        return;
                    }
                    resolve(rsp);
                } else if (xhr.readyState == 4) {
                    reject();
                } else {
                    // console.log("url=>" + url + " xhr.readyState=>" + xhr.readyState + "; status=>" + xhr.status);
                }
            }
            xhr.timeout = 8000;
            xhr.send();
        });
    }
    public static uploadImage(url: string, bs64:string, headers: any = null) {
        return new Promise((resolve: (data: HttpReturn) => void, reject) => {
            let xhr = new XMLHttpRequest();
            console.log(this.url + url);
            xhr.open("POST", this.url + url, true);
            StaticData.getToken() && xhr.setRequestHeader("X-Access-Token", StaticData.getToken());
            //xhr.setRequestHeader("Content-Type", "multipart/form-data");
            //xhr.setRequestHeader("img", bs64);
            let formData = new FormData();
            formData.append("img", bs64);
            if (headers) {
                for (let key in headers) {
                    xhr.setRequestHeader(key, headers[key]);
                }
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                    let response = xhr.responseText;
                    console.log(xhr.responseURL);
                    let rsp = JSON.parse(response);
                    resolve(rsp);
                } else if (xhr.readyState == 4) {
                    reject(); 
                } else {
                    // console.log("url=>" + url + " xhr.readyState=>" + xhr.readyState + "; status=>" + xhr.status);
                }
            }
            xhr.timeout = 8000;
            let data: any = { img: bs64 };
            xhr.send(formData);
        })

    }
}
class HttpReturn {
    public success: boolean;
    public result: any;
    public code: number;
    public message: string;
    public timestamp: string;
}